package com.situ.ymall.controller;

import com.situ.ymall.entity.User;
import com.situ.ymall.service.UserService;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.security.util.Password;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    //注入service层对象
    @Autowired
    private UserService userService;

    //跳转到注册页面
    @GetMapping("/reg")
    public String toreg(){
        return "user/reg";
    }
    /*
    用户注册
     */
    @PostMapping("/reg")
    public String reg(User user, String repassword, Model model){
        //获取参数
        //调用service层
        int result = userService.reg(user, repassword);
        //返回数据、获取页面
        if (result > 0){
            //注册成功
            //跳转到登录页面
            return "redirect:login";
        }else{
            //传递错误信息
            String error ="位置错误,请联系管理员";
            if (result == -1){
                error = "账号格式不正确";
            }else if(result == -2){
                error = "密码格式不正确";
            }else if (result == -3){
                error= "两次密码不一致";
            }else if (result == -4){
                error =  "账号不可用";
            }else if (result == -5){
                error = "密码不能为空";
            }
            model.addAttribute("error",error);
            //跳转注册页面    请求转发
            return "user/reg";
        }
    }

    //跳转到登录页面
    @GetMapping("/login")
    public String toLogin(){
        return "user/login";
    }

    /**
     * 登录
     * @param user
     * @param model
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(User user,Model model, HttpSession session){
        //1. 参数
        //2. service
        try {
            user = userService.login(user);

            //登录成功
            // 保存用户信息，到session中
            session.setAttribute("user",user);
            //跳转到主页
            return "redirect:/";
        } catch (Exception e) {
            //登录失败
            model.addAttribute("error",e.getMessage());
            // 回到登录页面
            return "user/login";
        }
    }

    /**
     * 退出登录,清空session
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        //清除session
        session.invalidate();
        //跳转页面
        return "redirect:/";
    }

    @GetMapping("/edit")
    public String edit(){
        return "user/edit";
    }

}
